import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserInfo } from '@/stores/modules/user'
import { baseURL } from '@/utils/config.js'
/**
 * pinia-公共数据区
 */

// const { token } = storeToRefs(userStore)
const axiosInstance = axios.create({
  baseURL,
  timeout: 1000
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const userStore = useUserInfo()
    const { getToken } = userStore
    const token = getToken()
    console.log(token)
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res) => {
    const { data } = res

    if (data.code !== 0) {
      ElMessage({
        showClose: true,
        message: data.message,
        type: 'error'
      })
      return Promise.reject(data.message)
    }
    return data
  },
  (err) => {
    return Promise.reject(err)
  }
)
export default axiosInstance
